package exemplo.database;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import exemplo.model.Sale;


public class SaleDAO extends DataBaseConnection{
	
	private ProductDAO prodDAO = new ProductDAO();
	private LoginDAO loginDAO = new LoginDAO();
	
	public SaleDAO() throws SQLException, ClassNotFoundException {
		super();
	}
	
	public boolean add(Sale sale) throws SQLException, ClassNotFoundException {
		PreparedStatement ps = getPreparedStatement("INSERT INTO sales VALUES (?, ?, ?, ?, ?, ?);");
		ps.setInt(1, sale.getCode());
		ps.setInt(2, sale.getProduct().getCode());
		ps.setString(3, sale.getAddress());
		ps.setInt(4, sale.getVendor().getCode());
		ps.setDate(5, new java.sql.Date(Calendar.getInstance().getTimeInMillis()));
		ps.setDouble(6, sale.getPrice());
		int b = ps.executeUpdate();
		ps.close();
		return b > 0;
	}

	public boolean delete(Sale sale) throws SQLException, ClassNotFoundException {
		PreparedStatement ps = getPreparedStatement("DELETE FROM sales WHERE code = ?;");
		ps.setInt(1, sale.getCode());
		int b = ps.executeUpdate();
		ps.close();
		return b > 0;	
	}
	
	public List<Sale> getSales() throws SQLException, ClassNotFoundException {
		List<Sale> list = new LinkedList<Sale>();
		ResultSet rs = getStatement().executeQuery("SELECT * FROM sales");
		while (rs.next()) {
			Sale sale = new Sale();
			populateSale(sale, rs);
			list.add(sale);
		}
		rs.close();
		return list;
	}
	
	private void populateSale(Sale sale, ResultSet rs) throws SQLException, ClassNotFoundException {
		sale.setAddress(rs.getString("address"));
		sale.setCode(rs.getInt("code"));
		sale.setDate(rs.getDate("date"));
		sale.setProduct(prodDAO.getByCode(rs.getInt("product")));
		sale.setVendor(loginDAO.getById(rs.getInt("vendor")));
	}
}
